#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdbool.h>

#define BUFFER_SIZE 255

int main(int argc, char **argv) {
	int socket_handle;
	struct sockaddr_in echo_server;
	struct sockaddr_in echo_client;
	char buffer[BUFFER_SIZE];
	unsigned int echo_length, client_length, server_length;
	int received = 0;

	if (argc < 2) {
		fprintf(stderr, "Not enough arguments: <port>\n");
		return 1;
	}

	if ((socket_handle = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		fprintf(stderr, "Couldn't create socket.\n");
		return 1;
	}

	memset(&echo_server, 0, sizeof(echo_server));
	echo_server.sin_family = AF_INET;
	echo_server.sin_addr.s_addr = htonl(INADDR_ANY);
	echo_server.sin_port = htons(atoi(argv[1]));

	server_length = sizeof(echo_server);
	if (bind(socket_handle, (struct sockaddr *) &echo_server, server_length) < 0) {
		fprintf(stderr, "Couldn't bind the server socket.\n");
		return 1;
	}

	while (true) {
		client_length = sizeof(echo_client);
		if ((received = recvfrom(socket_handle, buffer, BUFFER_SIZE, 0, (struct sockaddr *) &echo_client, &client_length)) < 0) {
                	fprintf(stderr, "Couldn't receive message.\n");
			return 1;
		}
		printf("Client connected: %s\n", inet_ntoa(echo_client.sin_addr));
		if (sendto(socket_handle, buffer, received, 0, (struct sockaddr *) &echo_client, sizeof(echo_client)) != received) {
                	fprintf(stderr, "Wrong number of echoed bytes.\n");
			return 1;
              	}
	}
	return 0;
}
